package com.lzx.iteam.emotion;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.lzx.iteam.R;
import com.lzx.iteam.util.Constants;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Megan on 15/11/26.
 */
public class EmotionUtil {

    private Context mContext;
    private EditText mEditText;
    private LinearLayout mLlEmotionDots;
    private ViewPager mVpEmotion;
    private List<View> views = new ArrayList<View>();
    // 6列4行
    private int columns = 6;
    private int rows = 4;
    private List<String> staticFacesList;
    public EmotionUtil(Context context,EditText editText,LinearLayout llEmotionDots,ViewPager vpEmotion){
        this.mContext=context;
        this.mEditText=editText;
        this.mLlEmotionDots=llEmotionDots;
        this.mVpEmotion=vpEmotion;

    }



    /**
     * 初始化表情列表staticFacesList
     */
    public void initStaticFaces() {
        try {
            staticFacesList = new ArrayList<String>();
            //            String[] faces = getAssets().list("face/png");
            String[] faces = new String[52];
//            faces[0] = "emotion_del_normal.png";
            for (int i = 0; i < 52; i++) {
                faces[i] = "f_static_" + String.format("%03d", i ) + ".png";
            }
            //将Assets中的表情名称转为字符串一一添加进staticFacesList
            for (int i = 0; i < faces.length; i++) {
                staticFacesList.add(faces[i]);
            }
            //去掉删除图片
//            staticFacesList.remove("emotion_del_normal.png");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 初始表情 *
     */
    public void initViewPager() {
        // 获取页数
        for (int i = 0; i < getPagerCount(); i++) {
            views.add(viewPagerItem(i));
            /*ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(15, 15);
            mLlEmotionDots.addView(dotsItem(i), params);*/

            ImageView imageView = new ImageView(mContext);
            LinearLayout.LayoutParams vl = new LinearLayout.LayoutParams(Constants.dip2px(mContext, 8), Constants.dip2px(mContext,8));
            vl.setMargins(9, 0, 9, 0);
            imageView.setLayoutParams(vl);
            imageView.setBackgroundResource(R.drawable.emotion_dots);
            mLlEmotionDots.addView(imageView);
        }
        FaceVPAdapter mVpAdapter = new FaceVPAdapter(views);
        mVpEmotion.setAdapter(mVpAdapter);
        mLlEmotionDots.getChildAt(0).setSelected(true);
    }

    /**
     * 表情页改变时，dots效果也要跟着改变
     */
   public class PageChange implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            for (int i = 0; i < mLlEmotionDots.getChildCount(); i++) {
                mLlEmotionDots.getChildAt(i).setSelected(false);
            }
            mLlEmotionDots.getChildAt(arg0).setSelected(true);
        }

    }


    private View viewPagerItem(int position) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.face_gridview, null);//表情布局
        GridView gridview = (GridView) layout.findViewById(R.id.chart_face_gv);
        /**
         * 注：因为每一页末尾都有一个删除图标，所以每一页的实际表情columns *　rows　－　1; 空出最后一个位置给删除图标
         * */
        List<String> subList = new ArrayList<String>();
        subList.addAll(staticFacesList
                .subList(position * (columns * rows - 1),
                        (columns * rows - 1) * (position + 1) > staticFacesList
                                .size() ? staticFacesList.size() : (columns
                                * rows - 1)
                                * (position + 1)));
        /**
         * 末尾添加删除图标
         * */
        subList.add("emotion_del_normal.png");
        FaceGVAdapter mGvAdapter = new FaceGVAdapter(subList, mContext);
        gridview.setAdapter(mGvAdapter);
        gridview.setNumColumns(columns);
        // 单击表情执行的操作
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    String png = ((TextView) ((LinearLayout) view).getChildAt(1)).getText().toString();
                    if (!png.contains("emotion_del_normal")) {// 如果不是删除图标
                        insert(getFace(png));
                    } else {
                        delete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        return gridview;
    }

    /**
     * 根据表情数量以及GridView设置的行数和列数计算Pager数量
     *
     * @return
     */
    private int getPagerCount() {
        int count = staticFacesList.size();
        return count % (columns * rows - 1) == 0 ? count / (columns * rows - 1)
                : count / (columns * rows - 1) + 1;
    }


    /**
     * 向输入框里添加表情
     */
    private void insert(CharSequence text) {
        int iCursorStart = Selection.getSelectionStart((mEditText.getText()));
        int iCursorEnd = Selection.getSelectionEnd((mEditText.getText()));
        if (iCursorStart != iCursorEnd) {
            ((Editable) mEditText.getText()).replace(iCursorStart, iCursorEnd, "");
        }
        int iCursor = Selection.getSelectionEnd((mEditText.getText()));
        ((Editable) mEditText.getText()).insert(iCursor, text);
    }

    /**
     * 删除图标执行事件
     * 注：如果删除的是表情，在删除时实际删除的是tempText即图片占位的字符串，所以必需一次性删除掉tempText，才能将图片删除
     */
    private void delete() {
        if (mEditText.getText().length() != 0) {
            int iCursorEnd = Selection.getSelectionEnd(mEditText.getText());
            int iCursorStart = Selection.getSelectionStart(mEditText.getText());
            if (iCursorEnd > 0) {
                if (iCursorEnd == iCursorStart) {
                    if (isDeletePng(iCursorEnd)) {
                        String st = "#[face/png/f_static_000.png]#";
                        ((Editable) mEditText.getText()).delete(
                                iCursorEnd - st.length(), iCursorEnd);
                    } else {
                        ((Editable) mEditText.getText()).delete(iCursorEnd - 1,
                                iCursorEnd);
                    }
                } else {
                    ((Editable) mEditText.getText()).delete(iCursorStart,
                            iCursorEnd);
                }
            }
        }
    }

    /**
     * 判断即将删除的字符串是否是图片占位字符串tempText 如果是：则讲删除整个tempText
     * *
     */
    private boolean isDeletePng(int cursor) {
        String st = "#[face/png/f_static_000.png]#";
        String content = mEditText.getText().toString().substring(0, cursor);
        if (content.length() >= st.length()) {
            String checkStr = content.substring(content.length() - st.length(),
                    content.length());
            String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(checkStr);
            return m.matches();
        }
        return false;
    }


    //png---face/png/f_static_001.png
    private SpannableStringBuilder getFace(String png) {
        SpannableStringBuilder sb = new SpannableStringBuilder();
        try {
            /**
             * 经过测试，虽然这里tempText被替换为png显示，但是但我单击发送按钮时，获取到輸入框的内容是tempText的值而不是png
             * 所以这里对这个tempText值做特殊处理
             * 格式：#[face/png/f_static_000.png]#，以方便判斷當前圖片是哪一個
             * */
            String tempText = "#[" + png + "]#";
            sb.append(tempText);
            //读assets中文件
            /*sb.setSpan(
                    new ImageSpan(SendTalkActivity.this, BitmapFactory
                            .decodeStream(getAssets().open(png))), sb.length()
                            - tempText.length(), sb.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);*/
            //读drawable中文件
            int resID = mContext.getResources().getIdentifier(png.split("/")[2].substring(0, png.split("/")[2].indexOf(".")), "drawable", mContext.getApplicationInfo().packageName);
            sb.setSpan(new ImageSpan(mContext, BitmapFactory.decodeResource(mContext.getResources(), resID)), sb.length()
                            - tempText.length(), sb.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sb;//#[face/png/f_static_001.png]#
    }

    private ImageView dotsItem(int position) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.dot_image, null);
        ImageView iv = (ImageView) layout.findViewById(R.id.face_dot);
        iv.setId(position);
        return iv;
    }


}
